package com.ggk911.pharmacy_system.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ggk911.pharmacy_system.entity.DTO.DrugInfoDTO;
import com.ggk911.pharmacy_system.entity.DrugInfo;
import com.ggk911.pharmacy_system.entity.DrugPrice;
import com.ggk911.pharmacy_system.entity.Supplier;
import com.ggk911.pharmacy_system.service.impl.SupplierServiceImpl;
import com.ggk911.pharmacy_system.util.RestResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * 供应商
 *
 * @author ggk-911
 * @version 1.0 2023/3/9 10:44
 */
@Slf4j
@RestController
@CrossOrigin
@RequiredArgsConstructor
@RequestMapping("/supplier")
@Api(tags = "供应商控制层")
public class SupplierController {
    private final SupplierServiceImpl service;

    //GET查询
    @GetMapping("/queryAll")
    public RestResult queryAll(@RequestParam(defaultValue = "1") Integer page,
                               @RequestParam(defaultValue = "10") Integer size,
                               @RequestParam(defaultValue = "") @ApiParam("搜索关键供应商名称") String name,
                               @RequestParam(defaultValue = "") @ApiParam("搜索关键供应商地址") String addr) {
        Page<Supplier> supplierPage = new Page<>(page, size);
        LambdaQueryWrapper<Supplier> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(!"".equals(name), Supplier::getSupplierName, name);
        wrapper.like(!"".equals(addr), Supplier::getSupplierAddr, addr);
        service.page(supplierPage, wrapper);
        return RestResult.ok("供应商查询成功", supplierPage);
    }

    //GET获取所有数据集合
    @GetMapping("/list")
    public RestResult getList(@RequestParam(defaultValue = "") @ApiParam("搜索关键供应商名称") String name,
                              @RequestParam(defaultValue = "") @ApiParam("搜索关键供应商地址") String addr) {
        LambdaQueryWrapper<Supplier> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(!"".equals(name), Supplier::getSupplierName, name);
        wrapper.like(!"".equals(addr), Supplier::getSupplierAddr, addr);
        List<Supplier> supplierList = service.list(wrapper);
        return RestResult.ok("获取成功", supplierList);
    }

    //GET查询单个供应商
    @GetMapping("/query/{id}")
    public RestResult queryOne(@PathVariable Integer id) {
        Supplier supplier = null;
        try {
            supplier = service.getById(id);
        } catch (Exception e) {
            log.error("查询单个供应商错误：" + e);
            return RestResult.error("查询单个供应商错误：");
        }
        return RestResult.ok("供应商查询成功", supplier);
    }

    //PUT插入
    @PutMapping("/insert")
    public RestResult insert(Supplier supplier) {
        try {
            //判断空 重复和 长度 添加
            if (service.selectBySupplierLicense(supplier.getSupplierLicense()) == null && supplier.getSupplierLicense().length() != 9 && service.save(supplier)) {
                return RestResult.ok("插入成功，返回供应商编号:" + supplier.getSupplierId(), supplier.getSupplierId());
            }
        } catch (Exception e) {
            log.error(String.valueOf(e));
        }
        return RestResult.error("插入失败，检查输入");
    }

    //DELETE删除
    @DeleteMapping("/delete")
    public RestResult delete(@ApiParam("要批量删除的供应商编号,用数组装") Integer[] ids) {
        log.info("删除供应商，编号为：" + Arrays.toString(ids));
        if (ids == null) return RestResult.error("删除失败,编号为空");
        //将数组转为集合
        if (!service.removeBatchByIds(Arrays.asList(ids))) return RestResult.error("删除失败");
        return RestResult.ok("删除成功");
    }

    //POST更新
    @PostMapping("/update")
    public RestResult update(@ApiParam("要更新的供应商") Supplier supplier) {
        try {
            if (service.updateById(supplier)) return RestResult.ok("更新成功");
        } catch (Exception e) {
            log.error(String.valueOf(e));
        }
        log.info("更新后的供应商：" + supplier);
        return RestResult.error("更新失败");
    }


    //POST表格导入
    @SneakyThrows
    @PostMapping("/importExcel")
    public RestResult importExcel(MultipartFile file) {

        //逻辑暂时放在controller
        if (file.isEmpty()) {
            throw new RuntimeException("上传文件为空");
        }
        ImportParams importParams = new ImportParams();
        importParams.setTitleRows(1);
        importParams.setHeadRows(1);
        InputStream inputStream = file.getInputStream();
        List<Supplier> list = ExcelImportUtil.importExcel(inputStream, Supplier.class, importParams);
        //拿到要导入的信息长度
        int size1 = list.size();
        inputStream.close();
        List<Supplier> supplierList = new ArrayList<>();
        list.forEach(item -> {
            //查询是否重复
//            Supplier supplierTest = service.selectBySupplierLicense(item.getSupplierLicense());
            //判断空 重复 重复要判断数据库里的重复和这个supplierList里的重复
            if (item.getSupplierLicense() != null && !"".equals(item.getSupplierLicense()) && item.getSupplierLicense().length() == 9 && service.selectBySupplierLicense(item.getSupplierLicense()) == null) {
                //sL重复判断标志
                boolean flag = true;
                //遍历sL
                for (int i = 0; i < supplierList.size(); i++) {
                    //sL里有重复就直接false且跳出
                    if (supplierList.get(i).getSupplierLicense().equals(item.getSupplierLicense())) {
                        flag = false;
                        break;
                    }
                }
                //判断重复
                if (flag) {
                    supplierList.add(item);
                }
            }
        });
        //筛选后的长度
        int size = supplierList.size();
        if (size == 0) return RestResult.error("表中无数据或数据重复");
        supplierList.forEach(System.out::println);
        if (service.saveBatch(supplierList)) {
            return RestResult.ok("批量导入成功，总：" + size1 + ",成功导入：" + size);
        }
        return RestResult.error("批量导入失败");
    }
}
